from django_filters.rest_framework import DjangoFilterBackend

from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.filters import SearchFilter
from rest_framework.filters import OrderingFilter
from rest_framework import status

from XApiTestServer.pagination import MyPageNumberPagination
from XApiTestServer.serializers import SuiteSerializer, SuiteSumSerializer

from XApiTestServer.utils.common import *
from XApiTestServer.utils.test_report import *
from XApiTestServer.utils.response import *
from XApiTestServer.utils.convertor import *
from XApiTestServer.utils.auth import get_username

import logging


logger = logging.getLogger('HttpRunnerManager')


def get_unique_test_list(test_list):
    """用例去重 需要吗？"""
    id_list = []
    ret_list = []
    for test in test_list:
        if test[0] not in id_list:
            ret_list.append(test)
            id_list.append(test[0])
    return ret_list


class SuiteViewSet(viewsets.ModelViewSet):
    queryset = TestSuite.objects.all()
    serializer_class = SuiteSerializer
    pagination_class = MyPageNumberPagination
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    search_fields = ('suite_name',)
    filterset_fields = ('belong_project',)
    ordering_fields = ('update_time', )

    def _name_validator(self, project_id, suitename, suite_id = None):
        if suite_id:
            actualname = TestSuite.objects.filter(id=suite_id).values('suite_name')
            if actualname[0]['suite_name'] == suitename:
                return False
            else:
                suitelist = TestSuite.objects.filter(belong_project=project_id).values('suite_name')
                for a in suitelist:
                    if a['suite_name'] == suitename:
                        return True
                    else:
                        continue
                return False
        else:
            suitelist = TestSuite.objects.filter(belong_project=project_id).values('suite_name')
            for a in suitelist:
                if a['suite_name'] == suitename:
                    return True
                else:
                    continue
            return False

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        response_body = SUCCESS_INFO
        response_body['data'] = serializer.data
        print(response_body['data'])
        response_body['data']['include'] = db_suite_to_vue(response_body['data']['include'])
        print(response_body['data']['include'])
        return Response(response_body)

    def create(self, request, *args, **kwargs):
        logger.info("create suite request body: {}" .format(request.data))
        if not request.data['suite_name']:
            msg = '套件名称(suite_name)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)


        if not request.data['belong_project']:
            msg = '所属项目(belong_project)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)


        request.data['include'],  request.data['disabled_cnt'] = vue_suite_to_db(request.data['suite_case_list'])
        request.data['include'] = str(request.data['include'])

        token = request.META.get("HTTP_X_TOKEN", None)
        username=get_username(token)
        request.data['author'] = username

        if self._name_validator(request.data['belong_project'], request.data['suite_name']):
            return Response(SUITE_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            response_body = SUCCESS_ADD
            response_body['data'] = serializer.data
            return Response(response_body, status=status.HTTP_201_CREATED, headers=headers)
        else:
            logger.error('Edit Suite ERROR:{error_info}'.format(error_info=serializer.errors))
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        logger.info("update suite request body: {}" .format(request.data))
        if not request.data['suite_name']:
            msg = '套件名称(suite_name)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if not request.data['belong_project']:
            msg = '所属项目(belong_project)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        request.data['include'],  request.data['disabled_cnt'] = vue_suite_to_db(request.data['suite_case_list'])
        request.data['include'] = str(str(request.data['include']))

        token = request.META.get("HTTP_X_TOKEN", None)
        username=get_username(token)
        request.data['author'] = username

        if self._name_validator(request.data['belong_project'], request.data['suite_name'],request.data['id']):
            return Response(SUITE_EXISTS, status=status.HTTP_201_CREATED)


        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)

        if serializer.is_valid(raise_exception=True):
            self.perform_update(serializer)

            response_body = SUCCESS_UPDATE
            response_body['data'] = serializer.data
            return Response(response_body)
        else:
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        response_body = SUCCESS_DEL
        return Response(response_body)


class SuiteSumViewSet(viewsets.ModelViewSet):
    queryset = TestSuite.objects.all()
    serializer_class = SuiteSumSerializer
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    filterset_fields = ('suite_name',)
    ordering_fields = ('update_time',)

    def list(self, request, *args, **kwargs):
        queryset = TestSuite.objects.all()

        serializer = self.get_serializer(queryset, many=True)

        response_body = SUCCESS_LIST
        response_body['results'] = serializer.data

        return Response(response_body)
